import Vue from "vue";
import Vuex from "vuex";
import indexAdminRoute from "@/tool/adminRoute";
import indexAdminRouteMobile from "@/tool/adminRouteMobile";
Vue.use(Vuex);
// 前台状态管理
function isPC() {
  let flag = true;
  let userAgentInfo = navigator.userAgent;
  let Agents = [
    "Android",
    "iPhone",
    "SymbianOS",
    "Windows Phone",
    "iPad",
    "iPod"
  ];
  for (var v = 0; v < Agents.length; v++) {
    if (userAgentInfo.indexOf(Agents[v]) > 0) {
      flag = false;
      break;
    }
  }
  return flag;
}
function sessionStg(state) {
  window.sessionStorage.setItem("aState", JSON.stringify(state));
}
async function mergeData(ath) {
  let isPc = isPC();
  let routeList = [];
  if (isPc) {
    routeList = deepTraversal(indexAdminRoute.children);
  } else {
    routeList = deepTraversal(indexAdminRouteMobile.children);
  }
  let newRouterList = [];
  await routeList.forEach(item => {
    ath.forEach(i => {
      if (i.unique_key === item.name) {
        let obj = {
          id: i.id,
          pid: i.pid,
          meta: item.meta,
          path: item.path,
          name: item.name
        };
        if (i.ismenu == 1) {
          obj.meta.showMenu = true;
        } else {
          obj.meta.showMenu = false;
        }
        newRouterList.push(obj);
        return;
      }
    });
  });
  return trans_tree(newRouterList);
}
function trans_tree(jsonData) {
  //result存储json数据转为树形结构后的结果。
  //temp为临时对象，将json数据按照id值排序.
  //len是json长度，用于循环遍历结束的条件
  var result = [],
    temp = {},
    len = jsonData.length;
  for (var i = 0; i < len; i++) {
    // 以id作为索引存储元素，可以无需遍历直接快速定位元素
    temp[jsonData[i]["id"]] = jsonData[i];
  }
  for (var j = 0; j < len; j++) {
    var currentElement = jsonData[j];
    // 临时变量里面的当前元素的父元素，即pid的值，与找对应id值
    var tempCurrentElementParent = temp[currentElement["pid"]];
    // 如果存在父元素，即如果有pid属性
    if (tempCurrentElementParent) {
      // 如果父元素没有chindren键
      if (!tempCurrentElementParent["children"]) {
        // 设上父元素的children键
        tempCurrentElementParent["children"] = [];
      }
      // 给父元素加上当前元素作为子元素
      tempCurrentElementParent["children"].push(currentElement);
    }
    // 不存在父元素，意味着当前元素是一级元素
    else {
      result.push(currentElement);
    }
  }
  return result;
}
function deepTraversal(data) {
  const result = [];
  data.forEach(item => {
    const loop = data => {
      result.push({
        path: data.path,
        name: data.name,
        component: data.component,
        meta: data.meta
      });
      let child = data.children;
      if (child) {
        for (let i = 0; i < child.length; i++) {
          loop(child[i]);
        }
      }
    };
    loop(item);
  });
  return result;
}
//    获取rootSubmenuKeys
function getAllSubMenuKeyList() {
  let rootSubmenuKeys = [];
  indexAdminRoute.children.forEach(item => {
    if (item.children) {
      rootSubmenuKeys.push(item.name);
    }
  });
  return rootSubmenuKeys;
}

export default new Vuex.Store({
  state: {
    isPC: true, // 是否为pc端
    // 菜单栏
    activeHeaderMenu: ["home"], // header menu菜单
    allSubMenuKeyList: getAllSubMenuKeyList(), //所有的有子节点的menu Name
    openKey: [], // 侧边栏当前打开的菜单栏
    // 面包屑
    currentBreadcrumb: [], //当前的面包屑
    // router
    currentRouterName: "home", // 当前的Router名,
    isOperationPage: false, // 当前页面的是否为操作页面
    isLogin: false, //当前登录状态
    userInfo: {}, //个人信息
    name: "",
    athList: [], //个人权限列表
    spinning: false
  },
  actions: {
    changeIsPC(context, isPC) {
      context.commit("changeIsPC", isPC);
    },
    changeUserInfo(context, info) {
      context.commit("changeUserInfo", info);
    },
    changeSpinning(context, isLand) {
      context.commit("changeSpinning", isLand);
    },
    changeAthList(context, athList) {
      context.commit("changeAthList", athList);
    },
    changeName(context, name) {
      context.commit("changeName", name);
    },
    changeCurrentRouter(context, routerName) {
      context.commit("changeCurrentRouter", routerName);
    },
    changeActiveMenu(context, routerName) {
      context.commit("changeActiveMenu", routerName);
    },
    changeCurrentBreadcrumb(context, list) {
      context.commit("changeCurrentBreadcrumb", list);
    },
    changeOpenKey(context, list) {
      context.commit("changeOpenKey", list);
    },
    changeShowOperationPage(context, isShow) {
      context.commit("changeShowOperationPage", isShow);
    },
    changeLoginState(context, login) {
      context.commit("changeLoginState", login);
    }
  },
  mutations: {
    changeIsPC(state, isPC) {
      state.isPC = isPC;
      sessionStg(state);
    },
    changeUserInfo(state, info) {
      state.userInfo = info;
      sessionStg(state);
    },
    changeSpinning(state, isLand) {
      state.spinning = isLand;
      sessionStg(state);
    },
    changeAthList(state, list) {
      state.athList = list;
      sessionStg(state);
    },
    changeName(state, name) {
      state.name = name;
      sessionStg(state);
    },
    changeCurrentRouter(state, routerName) {
      state.currentRouterName = routerName;
      sessionStg(state);
    },
    changeActiveMenu(state, routerName) {
      state.activeHeaderMenu = [routerName];
      sessionStg(state);
    },
    changeCurrentBreadcrumb(state, list) {
      state.currentBreadcrumb = list;
      sessionStg(state);
    },
    changeOpenKey(state, list) {
      state.openKey = list;
      sessionStg(state);
    },
    changeShowOperationPage(state, isShow) {
      state.isOperationPage = isShow;
      sessionStg(state);
    },
    changeLoginState(state, login) {
      state.isLogin = login;
      sessionStg(state);
    }
  },
  getters: {
    getNavList: async state => {
      return await mergeData(state.athList);
    },
    getChildAth: state => {
      let info = [];
      state.athList.forEach(item => {
        if (item.level == 3 || item.level == 2) {
          info.push(item.unique_key);
        }
      });
      return info;
    },
    getPageAth: state => {
      let info = [];
      state.athList.forEach(item => {
        if (item.level == 2) {
          info.push(item.unique_key);
        }
      });
      return info;
    }
  }
});
